package com.neusoft.newelm.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.neusoft.newelm.bean.Admin;
import com.neusoft.newelm.bean.Role;
import com.neusoft.newelm.common.ElmException;
import com.neusoft.newelm.common.Pager;
import com.neusoft.newelm.common.Result;
import com.neusoft.newelm.service.AdminService;
import com.neusoft.newelm.service.RoleService;
import com.neusoft.newelm.util.PasswordUtils;

/**
 * @RestController 的方法默认会返回json数据
 * 
 * @author chens
 *
 */
@RestController
@RequestMapping("/sys/admin")
public class AdminController {
	private Logger logger = Logger.getLogger(AdminController.class);

	@Autowired
	private AdminService adminService;
	@Autowired
	private RoleService roleService;

	@RequestMapping("login")
	public Admin login(HttpServletRequest request, HttpServletResponse response) {
		Admin temp = new Admin();
		String adminName = request.getParameter("adminName");
		String password = request.getParameter("password");
		String validate = request.getParameter("validate");

		Admin param = new Admin(null, adminName, password);
		try {
			String rand = (String) request.getSession().getAttribute("rand");
			// 使用验证码技术后，需要先校验验证码是否正确，在进行数据库校验；避免系统被机器暴露破解
			if (rand != null && rand.equals(validate)) {
				param = adminService.login(param);
				// 进行md5+盐值算法判断
				if (param != null && PasswordUtils.matches(param.getSalt(), password, param.getPassword())) {
					
					// 数据库验证成功，保存用户的session会话跟踪中
					temp = param;
					request.getSession().setAttribute("login_user", temp);
					// 用户登录成功后，使用cookie返回登录用户名称给客户端
					Cookie cookie = new Cookie("login_user", temp.getAdminName());
					cookie.setPath("/");
					response.addCookie(cookie);
				}
			}
		} catch (ElmException e) {
			e.printStackTrace();
		}
		return temp;
	}

	@RequestMapping("search")
	public Pager<Admin> list(@RequestParam(value = "page", defaultValue = "1") Integer page,
			@RequestParam(value = "rows", defaultValue = "10") Integer size) {
		Pager<Admin> pager = new Pager<>(page, size);

		logger.info(pager);

		int total = adminService.findTotal(pager);
		List<Admin> list = adminService.findByPager(pager);

		pager.setRows(list);
		pager.setTotal(total);
		logger.info(pager);

		return pager;
	}

	@RequestMapping("add")
	public Result add(Admin admin, MultipartFile file1, HttpSession session) {
		logger.info(" :::   " + admin);
		Result result = new Result();

		// 用户选择了上传的文件
		if (file1 != null && file1.getSize() > 0) {
			//获取或创建文件在服务器的保存路径
			String path = session.getServletContext().getRealPath("/");
			String uploadPath = "upload/images/";
			File pathFile = new File(path + uploadPath);
			pathFile.mkdirs();

			//修改上传后的文件名称
			String ofname = file1.getOriginalFilename();
			String fileType = ofname.substring(ofname.lastIndexOf("."));
			String newFileName = UUID.randomUUID() + fileType;
			File outputFile = new File(pathFile, newFileName);
			
			try {
				// 执行文件上传
				file1.transferTo(outputFile);
				// 上传成功，保存头像的相对地址
				admin.setHeadImage(uploadPath + newFileName);
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		// 新增用户时，生成随机盐值，并加密密码
		String salt = PasswordUtils.getSalt();
		String password = PasswordUtils.encode(admin.getPassword(), salt);

		// 把明文密码换成加密密码和加密盐一起更新
		admin.setSalt(salt);
		admin.setPassword(password);

		try {
			boolean ret = adminService.add(admin);
			if (ret) {
				result.setSuccess(true);
			} else {
				result.setErrorMsg("新增管理员失败");
			}
		} catch (ElmException e) {
			e.printStackTrace();
			result.setErrorMsg(e.getMessage());
		}

		return result;
	}

	@RequestMapping("edit")
	public Result edit(Admin admin, MultipartFile file1, HttpSession session) {
		logger.info(" :::   " + admin);
		Result result = new Result();

		// 用户选择了上传的文件
		if (file1 != null && file1.getSize() > 0) {
			String path = session.getServletContext().getRealPath("/");
			String uploadPath = "upload/images/";
			File pathFile = new File(path + uploadPath);
			pathFile.mkdirs();

			String ofname = file1.getOriginalFilename();
			String fileType = ofname.substring(ofname.lastIndexOf("."));
			String newFileName = UUID.randomUUID() + fileType;
			File outputFile = new File(pathFile, newFileName);
			try {
				// 执行文件上传
				file1.transferTo(outputFile);
				// 上传成功，保存头像的相对地址
				admin.setHeadImage(uploadPath + newFileName);
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		try {
			Admin temp = adminService.findById(admin.getAdminId());
			if (temp != null) {
				// 修改用户时，同时更新盐值和重新加密密码
				String salt = PasswordUtils.getSalt();
				String password = PasswordUtils.encode(admin.getPassword(), salt);
				temp.setSalt(salt);
				temp.setPassword(password);
				// 修改管理员的角色
				temp.setRoles(admin.getRoles());
				if(admin.getHeadImage()!=null) {
				   temp.setHeadImage(admin.getHeadImage());
				}

				boolean ret = adminService.edit(temp);
				if (ret) {
					result.setSuccess(true);
				} else {
					result.setErrorMsg("修改管理员失败");
				}
			} else {
				result.setErrorMsg("数据不存在");
			}

		} catch (ElmException e) {
			e.printStackTrace();
			result.setErrorMsg(e.getMessage());
		}
		return result;
	}

	@RequestMapping("del")
	public Result delete(Integer adminId) {
		Result result = new Result();

		if (adminId != null) {
			try {
				boolean ret = adminService.deleteById(adminId);
				if (ret) {
					result.setSuccess(Boolean.TRUE);
					result.setErrorMsg("删除成功");
				} else {
					result.setErrorMsg("删除失败");
				}
			} catch (ElmException e) {
				result.setErrorMsg(e.getMessage());
			}
		} else {
			result.setErrorMsg("用户不存在");
		}
		return result;
	}

	@RequestMapping("rolelist")
	public List<Role> findRole4Admin() {

		List<Role> list = roleService.findByPager(null);

		return list;
	}

}
